﻿using AnlianCommon.Common.Domains.UserPermissions;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AnlianCommon.API.Commands.Roles
{
    public class RoleQueryHandler : IRequestHandler<RoleQueryCommand,ResultPage<Role>>
    {
        private readonly IBaseRepository<Role> _rolesRepository;

        public RoleQueryHandler(IBaseRepository<Role> rolesRepository)
        {
            _rolesRepository = rolesRepository;
        }
        /// <summary>
        ///  业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultPage<Role>> Handle(RoleQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new ResultPage<Role>() { Code=(int)CommonErrorCode.Search,TotalCount=0,PagedCount=0};
            try
            {
                var roleList = await (await _rolesRepository.GetAll()).Where(c=>c.IsDeleted==false).ToListAsync();         
                if (!string.IsNullOrEmpty(request.RoleName))
                {
                    roleList = roleList.Where(c => c.RoleName.Contains(request.RoleName)).ToList();
                }
                result.TotalCount = roleList.Count;
                result.PagedCount = (int)Math.Ceiling((result.TotalCount * 1.0) / request.PageSize);
                roleList = roleList.OrderByDescending(c => c.RoleId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Data = roleList;
            }
            catch (Exception)
            {
                throw;
            }
            return result;
        }
    }
}
